package com.dbpms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dbpms.mapper.*;
import com.dbpms.pojo.*;
import com.dbpms.service.IStudentManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class StudentManageServiceImpl extends ServiceImpl<StudentManageMapper, StudentInfo> implements IStudentManageService {


    /**
     * 获取全部学院信息
     * @return
     */
    @Autowired
    private IStudentManageService iStudentManageService;
    @Resource
    private CollegeMapper collegeMapper;
    @Resource
    private StudentManageMapper studentManageMapper;

    /**
     * 获取学生信息
     * @param student_number : 学号  【 学号为null就开启分页，需要学号就不需要分页 】
     * @param page  ： 分页
     * @return
     */
    @Override
    public List<StudentInfo> queryStuInfo(String student_number,Page<StudentInfo> page) {
        // 学生数据
        List<StudentInfo> infos;
        // 按照学号查询
        if (student_number != null){
            QueryWrapper<StudentInfo> wrapper = new QueryWrapper<StudentInfo>()
                    .eq("student_number",student_number);
            infos = studentManageMapper.queryStdInfo_Page(null,wrapper);

        }else{

            QueryWrapper<StudentInfo> wrapper = new QueryWrapper<StudentInfo>()
                    .eq("1",1); // ew不能为null
            infos = studentManageMapper.queryStdInfo_Page(page,wrapper);
        }
        return infos;
    }
    /**
     * 获取学生id查询
     * @param stu_id : 学生id
     * @return
     */
    @Override
    public StudentInfo queryOneStuInfo(int stu_id) {
        // 学生数据
        StudentInfo info;
        QueryWrapper<StudentInfo> wrapper = new QueryWrapper<StudentInfo>()
                .eq("student_id",stu_id);
        info = studentManageMapper.queryStdInfo_Page(null,wrapper).get(0);
        return info;
    }

    @Override
    public List<CollegeInfo> queryCollegeInfo() {
        LambdaQueryWrapper<CollegeInfo> wrapper = new LambdaQueryWrapper<>();
        return collegeMapper.selectList(wrapper);
    }

    /**
     * 根据学院获取所属专业
     * @param college_id : 学院id
     * @return
     */
    @Resource
    private SpecialityMapper specialityMapper;
    @Override
    public List<SpecialityInfo> querySpecialityInfo(int college_id) {
        LambdaQueryWrapper<SpecialityInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SpecialityInfo::getSpecialityCollegeId,college_id);
        return specialityMapper.selectList(wrapper);
    }

    /**
     * 根据专业获取所属班级
     * @param speciality_id ：专业id
     * @return
     */
    @Resource
    private ClassMapper classMapper;
    @Override
    public List<ClassInfo> queryClassInfo(int speciality_id) {
        LambdaQueryWrapper<ClassInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClassInfo::getClassSpecialityId,speciality_id);
        return classMapper.selectList(wrapper);
    }

    /**
     * 添加学生信息 <- 事务
     * @param st
     * @return
     */
    @Override
    public String addStudentInfo(StudentInfo st) {
        String message = "true";
        try {
            // 添加学生
            save(st);

            // 寝室人员+1  update chamberinfo set chamber_number_of_people = chamber_number_of_people+1 where chamber_id = ?
            // 1.构造更新条件
            UpdateWrapper<ChamberInfo> wrapper = new UpdateWrapper<ChamberInfo>()
                    .setSql("chamber_number_of_people = chamber_number_of_people+1")
                    .in("chamber_id", st.getStudentChamberId());
            // 2.执行更新
            chamberInfoMapper.update(null,wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getCause().getMessage();
        }
        return message;
    }

    /**
     * 删除学生信息 <- 事务
     * @param stu_id ：学生id
     * @param chamber_id    ： 寝室id
     * @return
     */
    @Resource
    private ChamberMapper chamberInfoMapper;
    @Override
    public int deleteStudentInfo(int stu_id, int chamber_id,HttpServletRequest req) {

        // 删除图片
        StudentInfo info = iStudentManageService.queryOneStuInfo(stu_id);
        File file = new File(req.getServletContext().getRealPath("/img/")+info.getStudentImgName());
        file.delete();

        // 删除学生 DELETE FROM  studentinfo WHERE student_id = ?
        removeById(stu_id);

        // 制造异常
//        int i = 1/0;

        // 寝室空余人员+1  update chamberinfo set chamber_number_of_people = chamber_number_of_people-1 where chamber_id = ?
        // 1.构造更新条件
        UpdateWrapper<ChamberInfo> wrapper = new UpdateWrapper<ChamberInfo>()
                .setSql("chamber_number_of_people = chamber_number_of_people - 1")
                .in("chamber_id",chamber_id);
        // 2.执行更新
        return chamberInfoMapper.update(null,wrapper);
    }

    /**
     * 修改学生信息 <- 事务
     * @param st
     * @param chamber_id : 旧寝室id
     * @return
     */
    @Override
    public String updateStudentInfo(StudentInfo st, int chamber_id) {
        String message = "true";
        try {
            // 更新学生信息
            lambdaUpdate()
                    .set(StudentInfo::getStudentNumber,st.getStudentNumber()) // 学号
                    .set(StudentInfo::getStudentName,st.getStudentName()) // 姓名
                    .set(StudentInfo::getStudentGender,st.getStudentGender()) // 性别
                    .set(StudentInfo::getStudentAge,st.getStudentAge()) // 年龄
                    .set(StudentInfo::getStudentCollegeId,st.getStudentCollegeId()) // 学院
                    .set(StudentInfo::getStudentChamberId,st.getStudentChamberId()) // 寝室
                    .set(StudentInfo::getStudentFamilial,st.getStudentFamilial()) // 民族
                    .set(StudentInfo::getStudentIdCard,st.getStudentIdCard()) // 身份证
                    .set(StudentInfo::getStudentSpecialityId,st.getStudentSpecialityId()) // 专业
                    .eq(StudentInfo::getStudentId,st.getStudentId())
                    .update(); // 执行

            // 寝室表更新（旧寝室人数量-1）
            UpdateWrapper<ChamberInfo> wrapper_1 = new UpdateWrapper<ChamberInfo>()
                    .setSql("chamber_number_of_people= chamber_number_of_people - 1")
                    .in("chamber_id",chamber_id);
            chamberInfoMapper.update(null,wrapper_1);

            // 寝室表更新（新寝室人数量+1）
            UpdateWrapper<ChamberInfo> wrapper_2 = new UpdateWrapper<ChamberInfo>()
                    .setSql("chamber_number_of_people = chamber_number_of_people + 1")
                    .in("chamber_id",st.getStudentChamberId());

            chamberInfoMapper.update(null,wrapper_2);
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getCause().getMessage();
        }
        return message;
    }

    /**
     * 修改用户 - 学生信息
     * @param st
     * @return
     */
    @Override
    public String updateUserStuInfo(StudentInfo st) {
        String message = "true";
        try {
            // 更新学生信息
            LambdaUpdateChainWrapper<StudentInfo> eq = lambdaUpdate()
                    .set(StudentInfo::getStudentName, st.getStudentName()) // 姓名
                    .set(StudentInfo::getStudentGender, st.getStudentGender()) // 性别
                    .set(StudentInfo::getStudentAge, st.getStudentAge()) // 年龄
                    .set(StudentInfo::getStudentFamilial, st.getStudentFamilial()) // 民族
                    .set(StudentInfo::getStudentIdCard, st.getStudentIdCard()) // 身份证
                    .eq(StudentInfo::getStudentId, st.getStudentId());// 执行
            if (!st.getStudentImgName().equals("")) {
                eq.set(StudentInfo::getStudentImgName, st.getStudentImgName()); // 图片
            }
            eq.update();
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getCause().getMessage();
        }
        return message;
    }

    /**
     * 保存图片到指定目录下
     * @param imageFile : 图片文件
     * @param req   ： http
     * @return
     */
    @Override
    public File saveImg(MultipartFile imageFile, HttpServletRequest req) {
        // 文件名
        String ole_fileName = imageFile.getOriginalFilename();
        // 文件类型
        String fileType = ole_fileName.substring(ole_fileName.indexOf(".") + 1);
        // 新文件名
        String new_fileName = UUID.randomUUID()+"."+fileType;
        // 保存路径
        String filePath = req.getServletContext().getRealPath("/img/"); // D:\javaProject\Git\dbpms_ssm\target\dbpms_ssm\img\
        File dest = new File(filePath + new_fileName);
        try {
            imageFile.transferTo(dest); // 将图片文件保存到指定目录
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return dest;
    }
}
